import { Node, Rect, UITransform } from "cc";
import { ecs } from "db://app-game/libs/ecs/ECS";
import { ECSEntity } from "db://app-game/libs/ecs/ECSEntity";
import { Circle } from "db://app-game/libs/math/auad-tree/Circle";
import { QuadTree } from "db://app-game/libs/math/auad-tree/QuadTree";
import { MonitorGroupComp } from "../model/MonitorGroupComp";

/** 监视组系统 */
@ecs.register("MonitorGroup")
export class MonitorGroupSystem
  extends ecs.ComblockSystem
  implements ecs.ISystemUpdate
{
  filter(): ecs.IMatcher {
    return ecs.allOf(MonitorGroupComp);
  }

  update(entity: ECSEntity, dt: number): void {
    let monitorGroupData = entity.get(MonitorGroupComp);
    monitorGroupData.group.forEach((item) => {
      this.rebuildTree(entity, item.name);
    });
  }

  /** 重置四叉树 */
  rebuildTree(entity: ECSEntity, name: string) {
    let monitorGroupData = entity.get(MonitorGroupComp);
    const mapView =
      monitorGroupData.monitorNodes[name].getComponent(UITransform)!;
    const mapPosition = monitorGroupData.monitorNodes[name].worldPosition;
    const winSize = {
      x: mapPosition.x,
      y: mapPosition.y,
      width: mapView.width,
      height: mapView.height,
    };

    monitorGroupData.quadTreeObj[name] = new QuadTree(winSize, 0);

    monitorGroupData.monitorNodes[name]?.children.forEach((creature: Node) => {
      let rect = creature
        .getComponent(UITransform)
        ?.getBoundingBoxToWorld() as Rect;
      const rectangle = new Circle({
        x: creature.position.x,
        y: creature.position.y,
        xr: rect.width / 2,
        yr: rect.height / 2,
        data: {
          node: creature,
        },
      });
      monitorGroupData.quadTreeObj[name]?.insert(rectangle);
    });
  }
}
